package com.syq.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.syq.cache.CategoriesCache;
import com.syq.constants.ResultCode;
import com.syq.dao.SysCategoryMapper;
import com.syq.event.CategoryEvent;
import com.syq.exceptions.AddException;
import com.syq.exceptions.DeleteDataException;
import com.syq.pojo.CheckNull;
import com.syq.pojo.CheckType;
import com.syq.pojo.SysCategory;
import com.syq.pojo.SysUserInfo;
import com.syq.service.SysCategoryService;
import com.syq.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Sun Yueqi
 * @version 1.00
 * @time 2022/5/29 22:14
 */
@Service
public class SysCategoryServiceImpl implements SysCategoryService {

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    private CategoriesCache categoriesCache;

    @Autowired
    public void setCategoriesCache(CategoriesCache categoriesCache) {
        this.categoriesCache = categoriesCache;
    }
    private SysCategoryMapper categoryMapper;

    @Autowired
    public void setCategoryMapper(SysCategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public void addCategory(SysCategory category) {
        Assert.isTrue(!category.isEmpty(CheckType.ADD),()->{
            throw new AddException("请输入类别", ResultCode.DATA_NULL);
        });

        SysUserInfo sysUserInfo = SecurityUtils.getUserinfo(false);
        categoryMapper.addCategory(category);
        context.publishEvent(new CategoryEvent());
    }

    @Override
    public PageInfo<SysCategory> findByPage(int pageSize, int pageNum) {
        List<SysCategory> categoryList= categoriesCache.getCategoryList(false);
        List<SysCategory> result = categoryList.stream()
                .skip((pageNum - 1) * pageSize)//跳过多少数据
                .limit(pageSize)//要多少数据
                .collect(Collectors.toList());
        PageHelper.startPage(pageNum,pageSize);//开启分页
        PageInfo<SysCategory> pageInfo=new PageInfo<>(result);//获取数据
        pageInfo.setTotal(categoryList.size());//设置大小
        return pageInfo;
    }

    @Override
    public void deleteById(Long cId) {
        Assert.isTrue(cId>0,()-> {
            throw new DeleteDataException("主键不符合要求",ResultCode.ID_NOTALLOWED);
        });

        SysUserInfo userinfo = SecurityUtils.getUserinfo(false);
        categoryMapper.deleteById(cId,new Date(), userinfo.getUsername());
        context.publishEvent(new CategoryEvent());
    }
}
